package com.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java.entity.Dish;
import com.java.entity.Order;
import com.java.entity.OrderDetail;
import com.java.entity.R;
import com.java.service.IDishService;
import com.java.service.IOrderDetailService;
import com.java.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 * @author 
 * @site 

 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IDishService dishService;
    @Autowired
    private IOrderDetailService orderDetailService;

    /**
     * 创建订单
     * @param order 订单对象
     * @return 返回操作结果
     */
    @RequestMapping("/create")
    public R create(@RequestBody Order order){
        // System.out.println("order:"+order);
        order.setOrder_time(new Date());
        orderService.save(order);
        System.out.println(order.getId());
        for(OrderDetail od:order.getGoods_list()) {
            od.setMId(order.getId());
            orderDetailService.save(od);
            //菜品销量加1
            // Retrieve the dish associated with the order detail
            Dish dish = dishService.getOne(new QueryWrapper<Dish>().eq("name", od.getName()));
            // Increment the sales volume of the dish
            dish.setMonthlysale(dish.getMonthlysale() + 1);
            // Save the updated dish information back to the database
            dishService.updateById(dish);
        }
        return R.ok();
    }

    /**
     * 根据条件获取订单
     * @param table_number
     * @param transac_status
     * @return
     */
    @RequestMapping("/get")
    public R get(String table_number,String transac_status){
        Order order=orderService.list(new QueryWrapper<Order>().eq("table_number", table_number).eq("transac_status", transac_status).orderByDesc("order_time")).get(0);
        System.out.println("11:"+order);
        List<OrderDetail> goods_list = orderDetailService.list(new QueryWrapper<OrderDetail>().eq("mId", order.getId()));
        Map<String,Object> map=new HashMap<>();
        map.put("goods_list",goods_list);
        map.put("menu",order);
        return R.ok(map);
    }


}
